package com.objk.admin.security.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.obj.commpont.common.vo.ServerResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static com.objk.admin.security.constans.LoginResponseCode.CAPTCHA_CODE_EXPIRE_ERROR;

/**
 * 图形验证码过滤器
 *
 * @author yuan 2019/6/20 10:01
 */
@Component
@Slf4j
public class ValidateCodeFilter extends OncePerRequestFilter {

    private static final String POST = "POST";

    private static final String URL = "/admin/login";

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String currentUrl = request.getRequestURL().toString();
        if (new AntPathRequestMatcher(URL).matches(request) && request.getMethod().equals(POST)) {
            String captchaToken = request.getParameter("captchaToken");
            String captchaCode = request.getParameter("captchaCode");
            if (StringUtils.isBlank(captchaCode)) {
                this.responseError(response, ServerResponse.createByErrorMessage("验证码为空"));
                return;
            }
            String redisCaptchaToken = redisTemplate.opsForValue().get("user:captcha:" + captchaToken);
            // 图片验证码错误或过期
            if (StringUtils.isBlank(redisCaptchaToken) || !StringUtils.equalsIgnoreCase(captchaCode, redisCaptchaToken)) {
                this.responseError(response, ServerResponse.createByResponseCode(CAPTCHA_CODE_EXPIRE_ERROR));
                return;
            }
            log.info("图片验证码校验成功，{}", captchaCode);
        }
        filterChain.doFilter(request, response);
    }

    private void responseError(HttpServletResponse response, ServerResponse serverResponse) throws IOException {
        response.setStatus(HttpStatus.OK.value());
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(objectMapper.writeValueAsString(serverResponse));
    }
}
